from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import time
import datetime
import cgi
import datetime
import wsgiref.handlers
import os

from models import WordList
from models import WordUser

from kingsoft_reader import *
def createUser(user):
  now =  datetime.datetime.now()
  wUser = WordUser(user=user)
  wUser.firstLogin = now
  wUser.lastLogin = now
  wUser.loginTime = 1
  wUser.put()

def userExists(user):
  query = db.Query(WordUser) 
  query.filter('user = ', user)
  result = query.fetch(limit=1)
  return len(result) == 1

def outputWords(out, wordlist):
  for r in wordlist:
    out.write('<table>')
    out.write( '<tr>')
    out.write( r.word )
    out.write( r.translation )
    #print r.translation.encode('utf-8')
    out.write( r.pronunciation )
    out.write( r.flag )
    out.write( r.weight )
    out.write( '</tr>' )
    out.write('</table>')

def addToWordList(word, user):
  w = WordList(
      word = word[0], 
      translation = word[1],
      pronunciation = word[2],
      flag = int(word[3]),
      weight = 0,
      owner = user
      )
  query = db.Query(WordList)
  query.filter('owner =', user).filter('word =', word[0])
  results = query.fetch(limit=1)
  if len(results) < 1:
    w.put()


#Mobile Page generator
class MobilePage(webapp.RequestHandler):
  def get(self):
    ###################
    # ITEM NUM EVERY PAGE
    ITEM_NUM = 60
    user = users.get_current_user()
    pageNum = self.request.get('page')
    if pageNum:
      pageNum = int(pageNum)
    else:
      pageNum = 1
    if pageNum < 1:
      pageNum = 1
    if user:
      user_nickname = user.nickname()
      if not userExists(user):   
        createUser(user)
      logout_url = users.create_logout_url(self.request.uri) 
      #
      query = db.Query(WordList)
      query.filter('owner =', user)
      count = query.count(60000)
      if ITEM_NUM < 1:
        ITEM_NUM = 1
      page_total = count / ITEM_NUM
      if ( count % ITEM_NUM != 0):
        page_total = page_total + 1
      if (pageNum > page_total):
        pageNum = page_total
      results = query.fetch(limit=ITEM_NUM, offset = ITEM_NUM * (pageNum - 1))
      pageLinkVector = []
      if page_total < 2:
        pageLinkVector = []
      elif page_total < 5:
        for i in range(0,page_total):
          pageLinkVector.append( i + 1 )
      else:
          if (pageNum < 5):
            for i in (range(0, 5)):
              pageLinkVector.append( i + 1 )
          elif (pageNum > page_total - 5):
            for i in (range(0, 5)):
              pageLinkVector.append(page_total - (5 - i))
          else:
            for i in (range(0, 5)):
              pageLinkVector.append( pageNum - 2 + i)

      template_values = {
          'logout_url': logout_url,
          'wordlist': results,
          'pageLinkVector': pageLinkVector,
          'pageNum': pageNum,
          }
      #print pageLinkVector
      #print pageNum
      file = 'v'
      file = file + '/mobile_page.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))
    else:
      login_url = users.create_login_url(self.request.uri)
      #302 or a href 
      #self.redirect(login_url)
      template_values = {
          'login_url': login_url
          }
      file = 'v'
      file = file + '/login.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))

#MainPage
class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()

    if user:
      user_nickname = user.nickname()
      #self.response.headers['Content-Type'] = 'text/html charset=utf-8'
      #self.response.out.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">')
      if not userExists(user):   
        createUser(user)
      logout_url = users.create_logout_url(self.request.uri) 
      #
      #self.response.out.write('<a href="')
      #self.response.out.write(logout_url)
      #self.response.out.write('" >logout</a>')
      #self.response.out.write(
      #'''<form id="upload" action="/upload" enctype="multipart/form-data" method="post">
          #<label for="file">File:</label> <input type="file" name="file" id="file" />
          #<input type="submit" value="Upload" />
         #</form>
      #'''
      #)
      #query = WordList.all()
      query = db.Query(WordList)
      query.filter('owner =', user)
      results = query.fetch(limit=500)
      template_values = {
          'logout_url': logout_url,
          'wordlist': results,
          }
      file = 'v'
      file = file + '/main.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))
    else:
      login_url = users.create_login_url(self.request.uri)
      #302 or a href 
      #self.redirect(login_url)
      template_values = {
          'login_url': login_url
          }
      file = 'v'
      file = file + '/login.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))

#WordDetail
class WordDetail(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    word = self.request.get('word')
    pageNum = self.request.get('from')
    if pageNum:
      pageNum = int(pageNum)
    else:
      pageNum = 1
    if pageNum < 1:
      pageNum = 1
    #
    if user:
      user_nickname = user.nickname()
      if not userExists(user):   
        createUser(user)
      logout_url = users.create_logout_url(self.request.uri) 
      query = db.Query(WordList)
      query.filter('owner =', user)
      results = query.fetch(limit=500)
      detail = '#'
      pronunciation = ''
      weight = 0
      for k in results:
        if k.word.strip() == word.strip():
          detail = k.translation
          pronunciation = k.pronunciation
          weight = k.weight
          break
      #detail
      template_values = {
          'logout_url': logout_url,
          'word': word,
          'detail': detail,
          'weight': weight,
          'pronunciation': pronunciation,
          'pageNum': pageNum,
          }
      file = 'v'
      file = file + '/word_detail.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))
    else:
      login_url = users.create_login_url(self.request.uri)
      #302 or a href 
      #self.redirect(login_url)
      template_values = {
          'login_url': login_url
          }
      file = 'v'
      file = file + '/login.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))

#AdminPage
class AdminPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if users.is_current_user_admin():
      self.response.headers['Content-Type'] = 'text/plain'
      self.response.out.write('user list\n')
      query = WordUser.all()
      results = query.fetch(limit = 500)
      id = 1
      for r in results:
        self.response.out.write(str(id) + ' username : ' + r.user.nickname() + '\temail : ' + r.user.email() + '\n')

        query = db.Query(WordList)
        query.filter('owner =', r.user)
        wordsLoaded = query.fetch(limit=500)
        for wo in wordsLoaded:
          self.response.out.write(wo.word + '\n')
        id = id + 1

#Upload
class Upload(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    if user:
      file_data = self.request.get("file")
      bin = db.Blob(file_data)
      file_size = len(bin)
      if file_size > 200 * 1024:
        return self.redirect('/upload_error')
      try:
        file_data = unicode(file_data, 'utf-16')
        array = strReader(file_data)
        if array != None:
          for word in array:
            if word != None:
              #[english word][translation][pronunciation][level]
              #print word[3]
              addToWordList(word, user)
      except:
        self.redirect('/upload_error')
      finally:
        pass
      #check more
      #add to word list table
      return self.redirect('/')
    else:
      return self.redirect('/upload_error')
#delete word
class DeleteWordControl(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    word = self.request.get('word')
    pageNum = self.request.get('from')
    if pageNum:
      pageNum = int(pageNum)
    else:
      pageNum = 1
    if pageNum < 1:
      pageNum = 1
    #
    if user:
      user_nickname = user.nickname()
      if not userExists(user):   
        createUser(user)
      logout_url = users.create_logout_url(self.request.uri) 
      query = db.Query(WordList)
      query.filter('owner =', user)
      results = query.fetch(500)
      for k in results:
        if k.word.strip() == word.strip():
          k.delete()
          break
      template_values = {
          'logout_url': logout_url,
          'pageNum': pageNum,
          }
      file = 'v'
      file = file + '/delete_suc.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))
    else:
      login_url = users.create_login_url(self.request.uri)
      #302 or a href 
      #self.redirect(login_url)
      template_values = {
          'login_url': login_url
          }
      file = 'v'
      file = file + '/login.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))

#Mark word
class MarkWordControl(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    word = self.request.get('word')
    level = self.request.get('level')
    pageNum = self.request.get('from')
    if pageNum:
      pageNum = int(pageNum)
    else:
      pageNum = 1
    if pageNum < 1:
      pageNum = 1
    #
    if user:
      user_nickname = user.nickname()
      if not userExists(user):   
        createUser(user)
      logout_url = users.create_logout_url(self.request.uri) 
      query = db.Query(WordList)
      query.filter('owner =', user)
      results = query.fetch(500)

      detail = '#'
      pronunciation = ''
      weight = 0
      for k in results:
        if k.word.strip() == word.strip():
          detail = k.translation
          pronunciation = k.pronunciation
          if level == '1':
            k.weight = 1
            k.put()
          elif level == '2':
            k.weight = 2
            k.put()
          elif level == '0':
            k.weight = 0
            k.put()
          weight = k.weight
          break
      template_values = {
          'logout_url': logout_url,
          'word': word,
          'detail': detail,
          'weight': weight,
          'pronunciation': pronunciation,
          'pageNum': pageNum,
          }
      file = 'v'
      file = file + '/word_detail.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))
      
    else:
      login_url = users.create_login_url(self.request.uri)
      #302 or a href 
      #self.redirect(login_url)
      template_values = {
          'login_url': login_url
          }
      file = 'v'
      file = file + '/login.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))


#UploadError
class UploadError(webapp.RequestHandler):
  def get(self):
    pass

class ImportFromFile(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()

    if user:
      template_values = {}
      file = 'v'
      file = file + '/import.html'
      path = os.path.join(os.path.dirname(__file__), file)
      self.response.out.write(template.render(path, template_values))
#deal with the url
application = webapp.WSGIApplication(
    [
      ('/', MainPage),
      ('/admin$', AdminPage),
      ('/upload$', Upload),
      ('/upload_error', UploadError),
      ('/import', ImportFromFile),
      ('/m$', MobilePage),
      ('/word_detail', WordDetail),
      ('/do_delete', DeleteWordControl),
      ('/do_make_word_level', MarkWordControl),
      ],
    debug=True
    )
#main
def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

